package cn.action;

import cn.entity.Employee;
import cn.service.common.EmployeeBiz;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpSession;
import java.util.Map;

public class LoginAction extends ActionSupport {
    private Employee employee;
    private EmployeeBiz employeeBiz;
    private String random;

    @Override
    public void validate() {
        Map session = ActionContext.getContext().getSession();
        Map request = (Map) ActionContext.getContext().get("request");
        String code = (String) session.get("CODE");
        if (random==null||random.length()==0||"".equals(random)){
            addFieldError("msg","请输入验证码");
            request.put("msg","请输入验证码");
        }else if(!random.equals(code.toLowerCase())){
            addFieldError("msg","验证码错误");
            request.put("msg","验证码错误");
        }
    }

    @Override
    public String execute() throws Exception {
        Employee emp = employeeBiz.login(employee.getSn());
        Map request = (Map) ActionContext.getContext().get("request");
        Map session = ActionContext.getContext().getSession();
        if (emp==null){
            request.put("msg","工号不存在");
            return INPUT;
        }else if (!emp.getPassword().equals(employee.getPassword())){
            request.put("msg","密码错误");
            return INPUT;
        }
        String status = emp.getStatus();
        if ("离职".equals(status)){
            request.put("msg","离职员工不能登录");
            return INPUT;
        }
        session.put("employee",emp);
        session.put("employee_position",emp.getSysPosition().getNameCn());
        return SUCCESS;
    }

    public String logOut(){
//        HttpSession session = ServletActionContext.getRequest().getSession();
        Map sessionMap = ActionContext.getContext().getSession();
        for (Object key:sessionMap.keySet()) {
            sessionMap.remove(key);
        }
//        session.invalidate();
        return SUCCESS;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

    public void setEmployeeBiz(EmployeeBiz employeeBiz) {

        this.employeeBiz = employeeBiz;
    }

    public void setRandom(String random) {
        this.random = random;
    }

    public Employee getEmployee() {
        return employee;
    }

    public EmployeeBiz getEmployeeBiz() {
        return employeeBiz;
    }

    public String getRandom() {
        return random;
    }
}
